﻿namespace CardGameCore.Battle
{
    public class PlayerAction : IPlayerAction
    {
        private readonly BattleEventsResult _result = new BattleEventsResult();
        private readonly IBattlefield _battlefield;
        private readonly IHorizontalFinder _horizontalFinder;
        private readonly IDamageHandler _damageHandler;
        
        public PlayerAction(
            IBattlefield battlefield,
            IHorizontalFinder horizontalFinder,
            IDamageHandler damageHandler)
        {
            _battlefield = battlefield;
            _horizontalFinder = horizontalFinder;
            _damageHandler = damageHandler;
        }

        public BattleEventsResult Process()
        {
            foreach (var position in _battlefield.Player.Positions)
            {
                if (!_battlefield.Player.BattleCards.ContainsKey(position))
                {
                    continue;
                }

                var card = _battlefield.Player.BattleCards[position];
                var target = GetTarget(card);
                _result.Events.Add(_damageHandler.Process(card, target));
                
                if (target is Card cardTarget && cardTarget.Hp == 0)
                {
                    _battlefield.Enemy.BattleCards.Remove(card.Position);
                }
            }
            return _result;
        }

        private object GetTarget(Card card)
        {
            if (!_horizontalFinder.TryGetHorizontalCard(
                _battlefield.Enemy, card.Position, out var target))
            {
                target = _battlefield.Enemy;
            }

            return target;
        }
    }
}